package net.wofly.sale.commission.service.impl;

import net.wofly.common.condition.Condition;
import net.wofly.common.condition.ConditionRelate;
import net.wofly.common.condition.FilterCondition;
import net.wofly.common.condition.Operation;
import net.wofly.common.persistence.PageWrapper;
import net.wofly.common.util.Identities;
import net.wofly.common.util.PageHelper;
import net.wofly.common.util.ResultCode;
import net.wofly.common.util.ReturnBean;
import net.wofly.right.domain.User;
import net.wofly.right.service.IUserService;
import net.wofly.sale.commission.domain.CommissionCfg;
import net.wofly.sale.commission.domain.OrderCommission;
import net.wofly.sale.commission.domain.SaleCommissionSum;
import net.wofly.sale.commission.repository.CommissionCfgRepository;
import net.wofly.sale.commission.service.ICommissionCfgService;
import net.wofly.sale.commission.service.IOrderCommissionService;
import net.wofly.sale.commission.service.ISaleCommissionSumService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.List;

@Service("iCommissionCfgService")
@Transactional
public class CommissionCfgServiceImpl implements ICommissionCfgService {

	@Autowired
	CommissionCfgRepository commissionCfgRepository;
	@Autowired
	IUserService iUserService;
	@Autowired
	IOrderCommissionService iOrderCommissionService;
	@Autowired
	ISaleCommissionSumService iSaleCommissionSumService;

	@Override
	public CommissionCfg save(CommissionCfg entity) {
		return commissionCfgRepository.save(entity);
	}

	@Override
	public void delete(CommissionCfg entity) {
		commissionCfgRepository.delete(entity);
	}

	@Override
	public void delete(String key) {
		commissionCfgRepository.delete(key);
	}

	@Override
	public CommissionCfg findOne(String key) {
		return commissionCfgRepository.findOne(key);
	}

	@Override
	public List<CommissionCfg> save(List<CommissionCfg> entityList) {
		return (List<CommissionCfg>) commissionCfgRepository.save(entityList);
	}

	@Override
	public ReturnBean<CommissionCfg> addCommissionCfg(CommissionCfg commissionCfg) {
		commissionCfg.setCommissionCfgID(Identities.uuid2());
		commissionCfg.setStatus(1);
		commissionCfg.setModifyDate(System.currentTimeMillis());
		return new ReturnBean<>(ResultCode.SUCCESS, "添加新的佣金配置成功", commissionCfgRepository.save(commissionCfg));
	}

	@Override
	public ReturnBean<CommissionCfg> delCommissionCfg(String commissionCfgID) {
		CommissionCfg commissionCfg = commissionCfgRepository.findOne(commissionCfgID);
		if (null == commissionCfg) {
			return new ReturnBean<>(ResultCode.ERROR_SERVICE, "未找到数据，删除失败！");
		}
		commissionCfg.setStatus(0);
		return new ReturnBean<>(ResultCode.SUCCESS, "删除佣金配置成功", commissionCfgRepository.save(commissionCfg));
	}

	@Override
	public ReturnBean<CommissionCfg> getCommissionRateByUser(String userID) {
		List<CommissionCfg> commissionCfgs = commissionCfgRepository.findByUserID(userID);
		if (commissionCfgs.size() == 0) {
			User user = iUserService.findOne(userID);
			if (null == user) {
				return new ReturnBean<>(ResultCode.ERROR_SERVICE, "未找到用户数据，获取用户佣金配置失败！");
			}

			commissionCfgs = commissionCfgRepository.findByRoleIDAndUserID(user.getRoleID(), "0");
			if (commissionCfgs.size() == 0) {
				return new ReturnBean<>(ResultCode.ERROR_SERVICE, "未找到用户佣金配置数据，获取用户佣金配置失败！");
			}
		}

		CommissionCfg commissionCfg = commissionCfgs.get(0);
		BigDecimal commissionRate = new BigDecimal(String.valueOf(commissionCfg.getCommissionRate()));
		BigDecimal denominator = new BigDecimal(String.valueOf(commissionCfg.getDenominator()));
		BigDecimal result = commissionRate.multiply(new BigDecimal("100")).divide(denominator).setScale(2, BigDecimal.ROUND_HALF_UP);
		commissionCfg.setCommissionRateStr(result.toString() + "%");

		return new ReturnBean<>(ResultCode.SUCCESS, "获取用户佣金配置成功", commissionCfg);
	}

	@Override
	public ReturnBean<PageWrapper<OrderCommission>> getSaleCommissionDetail(String userID, Long startTime, Long endTime, Integer pageNum, Integer pageSize) {
		Condition condition = new Condition();
		if (StringUtils.isNotBlank(userID)) {
			condition.addFirstFilter(new FilterCondition(userID, "saleUserID", ConditionRelate.and.name(), Operation.eq.name(), 1));
		}

		if (startTime != null && startTime > 0) {
			condition.addFirstFilter(new FilterCondition(String.valueOf(startTime), "modifyDate", ConditionRelate.and.name(), Operation.ge.name(), 2));
		}

		if (endTime != null && endTime > 0) {
			condition.addFirstFilter(new FilterCondition(String.valueOf(endTime), "modifyDate", ConditionRelate.and.name(), Operation.le.name(), 3));
		}

		// 获得分页对象pageable，并且在pageable中页码是从0开始，设定按照sortType升序排列
		Pageable pageable = new PageRequest(pageNum - 1, pageSize);
		Page<OrderCommission> page;
		if (condition != null) {
			page = iOrderCommissionService.findAll(condition.getSpecification(), pageable);
		} else {
			page = iOrderCommissionService.findAll(pageable);
		}
		return new ReturnBean<>(ResultCode.SUCCESS, "获取销售提成流水成功！", PageHelper.toPage(page));
	}

	@Override
	public ReturnBean<List<SaleCommissionSum>> getSaleCommissionMonthSum(Integer sumDuration, Long sumTime) {
		List<SaleCommissionSum> saleCommissionSumList = iSaleCommissionSumService.findBySumTimeAndSumDuration(sumTime, sumDuration);
		return new ReturnBean<>(ResultCode.SUCCESS, "获取销售提成月汇总成功！", saleCommissionSumList);
	}

	@Override
	public ReturnBean<CommissionCfg> updateCommissionCfg(CommissionCfg commissionCfg) {
		CommissionCfg updateCommissionCfg = commissionCfgRepository.findOne(commissionCfg.getCommissionCfgID());
		if (null != updateCommissionCfg) {
			updateCommissionCfg.setStatus(0);
			updateCommissionCfg.setModifyDate(System.currentTimeMillis());
			commissionCfgRepository.save(updateCommissionCfg);
		}
		commissionCfg.setCommissionCfgID(Identities.uuid2());
		commissionCfg.setStatus(1);
		commissionCfg.setModifyDate(System.currentTimeMillis());

		return new ReturnBean<>(ResultCode.SUCCESS, "更新佣金配置成功", commissionCfgRepository.save(commissionCfg));
	}
}
